﻿using LianChuDemo.IDal.BaseInfoManagerDal;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WenDangOne.Common.Lib.TypeTools;
using WenDangOne.DbModel.BaseInfoManager;
using WenDangOne.ViewModel.BaseInfoManagerView;
using WenDangOne.ViewModel.common;

namespace LianChuDemo.SqlServerDal.BaseInfoManagerDal
{
    public class AdminUserDal : BaseDal, IAdminUserDal
    {
        //注入ef的的上下文
        public AdminUserDal(SystemCenterDbContext systemCenterDbContext) : base(systemCenterDbContext)
        {

        }

        public AdminUser GetAdminUserByUserName(string userName)
        {
            //如果这个参数等于空，就返回空
            if (string.IsNullOrWhiteSpace(userName)) return null;
            //否则就返回查询到的第一条数据
            return _systemCenterDbContext.AdminUser.FirstOrDefault(p => p.user_name == userName);
        }

        public bool AdminUserAdd(AdminUserView view)
        {
            //命名空间，用于事务回滚，如果中途出现意外，就立即回滚数据
            using (var tran = _systemCenterDbContext.Database.BeginTransaction())
            {
                try
                {
                    AdminUser dbModel = ModelCopier.CreateInstanceFrom<AdminUser>(view);
                    _systemCenterDbContext.AdminUser.Add(dbModel);//添加进去
                    _systemCenterDbContext.SaveChanges();//然后提交，保存一下,可以获取到id
                    List<AdminUserRoleRelation> arrs = new List<AdminUserRoleRelation>();
                    //如果她不等于空或者他的长度大于0
                    if (view.roleIds != null && view.roleIds.Count > 0)
                    {
                        foreach (var roleId in view.roleIds)
                        {
                            //添加数据
                            arrs.Add(new AdminUserRoleRelation()
                            {
                                user_name = dbModel.user_name,
                                role_id = roleId,
                                creator_date = dbModel.creator_date,
                                creator_name = dbModel.creator_name
                            }
                                );
                        }
                        _systemCenterDbContext.AdminUserRoleRelation.AddRange(arrs);
                        _systemCenterDbContext.SaveChanges();//赋值之后在一次提交,用户和用户关系一起保存
                    }
                    tran.Commit();//提交事务
                    return true;
                }
                catch (Exception ex)
                {
                    tran.Rollback();//事务回滚，出现错误进行回滚
                    throw ex;//错误处理
                }
            }
        }

        public PagerResult<AdminUser> SearchPage(SearchModel searchModel)
        {
            //查询全部数据
            var query = _systemCenterDbContext.AdminUser.AsQueryable();
            //判断有没有搜索条件，他的内容是否不等于空和他的长度是否大于0，是的话就这样
            if (searchModel.SearchItem != null && searchModel.SearchItem.Count > 0)
            {
                //把搜索条件拿出来，searchModel是搜索条件的封装
                var tempDi = searchModel.SearchItem;

                //将user_name字段赋值给userName，为搜索字段
                string userName = "user_name";
                //判断搜索条件中是否有user_name这个
                if (tempDi.Keys.Contains(userName) && !string.IsNullOrEmpty(tempDi[userName]))
                {
                    //类似于like查询, 判断userName是否包含查询条件中的条件值
                    query = query.Where(c => c.user_name.Contains(tempDi[userName]));
                }
                string userFullName = "user_full_name";
                //判断搜索条件中是否有user_full_name这个
                if (tempDi.Keys.Contains(userFullName) && !string.IsNullOrEmpty(tempDi[userFullName]))
                {
                    //类似于like查询, 判断userFullName是否包含查询条件中的条件值
                    query = query.Where(c => c.user_full_name.Contains(tempDi[userFullName]));
                }
                string userStatus = "user_status";
                //判断搜索条件中是否有user_status
                if (tempDi.Keys.Contains(userStatus) && !string.IsNullOrEmpty(tempDi[userStatus]))
                {
                    int tempStatus = -1;
                    //无报错信息的转换数字方法
                    if (int.TryParse(tempDi[userStatus], out tempStatus))
                    {
                        query = query.Where(c => c.user_status == tempStatus);
                    }
                }
                //begin_creator_date  创建时间时间段查询的开始时间
                string beginCreatorDate = "begin_creator_date";
                //判断搜索条件中是否有user_status
                if (tempDi.Keys.Contains(beginCreatorDate) && !string.IsNullOrEmpty(tempDi[beginCreatorDate]))
                {
                    DateTime tempCreatorDate = new DateTime();
                    if (DateTime.TryParse(tempDi[beginCreatorDate], out tempCreatorDate))
                    {
                        //关于数字和时间都是用大于等于小于符号进行判断
                        query = query.Where(c => c.creator_date >= tempCreatorDate);
                    }
                }
                //begin_creator_date  创建时间时间段查询的开始时间
                string endCreatorDate = "end_creator_date";
                //判断搜索条件中是否有user_status
                if (tempDi.Keys.Contains(endCreatorDate) && !string.IsNullOrEmpty(tempDi[endCreatorDate]))
                {
                    DateTime tempCreatorDate = new DateTime();
                    if (DateTime.TryParse(tempDi[endCreatorDate], out tempCreatorDate))
                    {
                        query = query.Where(c => c.creator_date <= tempCreatorDate);
                    }

                }

                if (!string.IsNullOrEmpty(searchModel.OrderBy))
                {
                    if (searchModel.OrderBy == "creator_date")
                    {
                        if (searchModel.OrderByType == OrderByType.ASC)
                        {
                            query = query.OrderBy(c => c.creator_date);
                        }
                        else
                        {
                            query = query.OrderByDescending(c => c.creator_date);
                        }
                    }
                    if (searchModel.OrderBy == "user_full_name")
                    {
                        if (searchModel.OrderByType == OrderByType.ASC)
                        {
                            query = query.OrderBy(c => c.user_full_name);
                        }
                        else
                        {
                            query = query.OrderByDescending(c => c.user_full_name);
                        }
                    }
                }
            }
            //这里有个封装，就是总行数那个，分页，所以这里返回的是一个名字里面带两个参数，第一个数查询的所有数据，第二个是查询的数据
            return BasePageSearch(query, searchModel);
        }

        public AdminUserView GetAdminUserViewByUserName(string userName)
        {
            //判断它是不是空，返回null值
            if (string.IsNullOrWhiteSpace(userName)) return null;
            //获取？数据
            var dbUser = GetAdminUserByUserName(userName);
            //判断它是不是空，返回null值
            if (dbUser == null) return null;
            //把dbUser转化为view
            AdminUserView view = ModelCopier.CreateInstanceFrom<AdminUserView>(dbUser);
            //查数据，因为反填时返回的那个树，是id而不是名称,
            view.roles = (from r in _systemCenterDbContext.RoleDb
                          join aur in _systemCenterDbContext.AdminUserRoleRelation on r.role_id equals aur.role_id
                          where aur.user_name == userName
                          select r).ToList();
            //返回的是list类型集合
            if (view.roles != null && view.roles.Count > 0)
                view.roleIds = view.roles.Select(c => c.role_id).ToList();
            return view;
        }

        public bool AdminUserUpdate(AdminUserView view)
        {
            //判断是否等空，返回false
            if (view == null) return false;
            //事务
            using (var tran = _systemCenterDbContext.Database.BeginTransaction())
            {
                try
                {
                    //返回符合条件的第一条数据，如果没有就返回默认值
                    AdminUser dbModel = _systemCenterDbContext.AdminUser.FirstOrDefault(c => c.user_name == view.user_name);
                    //把数据拷过去，但是有几项不拷，就是后面写的那些
                    ModelCopier.CopyModel(view, dbModel, "creator_name", "creator_date",
                        "last_lgoin_date", "last_login_ip", "pass_word");
                    //删除的SQL语句
                    string sql = "delete admin_user_role_relation where user_name=({0})";
                    _systemCenterDbContext.Database.ExecuteSqlRaw(sql, view.user_name);
                    //应该是实例
                    List<AdminUserRoleRelation> arrs = new List<AdminUserRoleRelation>();
                    if (view.roleIds != null && view.roleIds.Count > 0)
                    {
                        foreach (var roleId in view.roleIds)
                        {
                            //条件判断然后循环，循环之后获取数据
                            arrs.Add(new AdminUserRoleRelation()
                            {
                                user_name = dbModel.user_name,
                                role_id = roleId,
                                creator_date = dbModel.modifi_date.Value,
                                creator_name = dbModel.modifi_name
                            });
                        }
                        _systemCenterDbContext.AdminUserRoleRelation.AddRange(arrs);//把数据添加进去

                    }
                    _systemCenterDbContext.SaveChanges(); //把用户和用户角色关系一起保存
                    //事务，表示成功
                    tran.Commit();
                    return true;

                }
                catch (Exception ex)
                {
                    //事务，表示失败
                    tran.Rollback();
                    throw ex;
                }


            }
        }

        public bool AdminUserPwdUpdate(string pwd, string userName)
        {
            AdminUser dbModel = _systemCenterDbContext.AdminUser.FirstOrDefault(c => c.user_name == userName);
            dbModel.pass_word = pwd;
            return _systemCenterDbContext.SaveChanges() > 0;
        }
    }
}
